$(function () {
    $("#tou").load("tou.html");

    //判断是否是管理员
    $.ajax({
        url: "easybuy/admin/jurisdiction",
        success: function (data) {
            if (data != "success") {
                alert("你没有权限访问！");
                location.href = "Index.html";
            }
        }
    });

    showProductList(1, 8);
});

//显示所有商品
function showProductList(pageNum, pageSize) {
    $.ajax({
        url: "easybuy/selectAllProduct",
        data: {
            pageNum: pageNum,
            pageSize: pageSize
        },
        success: function (data) {
            $("#products").empty();
            $("#products").append("<tr>\n" +
                "                    <th width=\"23%\">商品名称</th>\n" +
                "                    <th width=\"22%\">商品图片</th>\n" +
                "                    <th width=\"15%\">库存</th>\n" +
                "                    <th width=\"15%\">价格</th>\n" +
                "                    <th width=\"25%\">操作</th>\n" +
                "                </tr>");

            $.each(data.list, function (index, product) {


                if (product.isdelete==0){
                    $("#products").append("<tr style='line-height: 70px;'>\n" +
                        "                    <td width=\"23%\">" + product.name + "</td>\n" +
                        "                    <td width=\"22%\"><img src='http://47.104.137.246:9999/files/" + product.filename + "' style='height: 50px'></td>\n" +
                        "                    <td width=\"15%\">" + product.stock + "</td>\n" +
                        "                    <td width=\"15%\">￥" + product.price + "</td>\n" +
                        "                    <td width=\"25%\">" +
                        "                       <a href='javascript:;' class='delete' data-id='" + product.id + "'>下架</a>" +
                        "                    </td>\n" +
                        "                </tr>");
                }
                else if (product.isdelete==1){
                    $("#products").append("<tr style='line-height: 70px;'>\n" +
                        "                    <td width=\"23%\">" + product.name + "</td>\n" +
                        "                    <td width=\"22%\"><img src='http://47.104.137.246:9999/files/" + product.filename + "' style='height: 50px'></td>\n" +
                        "                    <td width=\"15%\">" + product.stock + "</td>\n" +
                        "                    <td width=\"15%\">￥" + product.price + "</td>\n" +
                        "                    <td width=\"25%\">" +
                        "                       <a href='javascript:;' class='update' data-id='" + product.id + "' data-categorylevel1id='"+product.categorylevel1id+"' data-categorylevel2id='"+product.categorylevel2id+"' data-categorylevel3id='"+product.categorylevel3id+"'>修改</a>&nbsp;&nbsp;&nbsp;&nbsp;" +
                        "                   <a href='javascript:;' class='putaway' data-id='" + product.id + "' style='color: red'>上架</a>" +
                        "                    </td>\n" +
                        "                </tr>");

                }

            });

            getPage(pageNum, pageSize, data);

            //删除
            $(".delete").click(function () {
                deleteProduct($(this).data("id"));
            });
            //跳转到修改页面
            $(".update").click(function () {
                var id=$(this).data("id");
                var categorylevel1id=$(this).data("categorylevel1id");
                var categorylevel2id=$(this).data("categorylevel2id");
                var categorylevel3id=$(this).data("categorylevel3id");
                updateProduct(id,categorylevel1id,categorylevel2id,categorylevel3id);
            });

            //上架
            $(".putaway").click(function () {
                GoodsShelves($(this).data("id"));
            });
        }
    })
}

//分页
function getPage(pageNum, pageSize, data) {
    $(".pages").empty();

    //首页
    $(".pages").append("<a href=\"javascript:;\" class=\"p_pre\" id='homePage'>首页</a>");

    $("#homePage").click(function () {
        showProductList(1, pageSize);
    });

    //上一页
    if (pageNum > 1) {
        $(".pages").append("<a href=\"javascript:;\" class=\"p_pre\" id='pre'>上一页</a>");
        $("#pre").click(function () {
            showProductList(pageNum - 1, pageSize);
        })
    }

    //页数
    for (let i = 0; i < data.navigatepageNums.length; i++) {
        if (pageNum == i + 1) {
            $(".pages").append("<a href=\"javascript:;\" class=\"cur number\">" + (data.navigatepageNums[i]) + "</a>");
        } else {
            $(".pages").append("<a href=\"javascript:;\" class='number'>" + (data.navigatepageNums[i]) + "</a>");
        }
    }
    $(".number").click(function () {
        var pageNum = $(this).text();
        showProductList(pageNum, pageSize)
    })

    //下一页
    if (pageNum < data.pages) {
        $(".pages").append("<a href=\"javascript:;\" class=\"p_pre\" id='next'>下一页</a>");
        $("#next").click(function () {
            showProductList(pageNum + 1, pageSize)
        })
    }
    //末页
    $(".pages").append("<a href=\"javascript:;\" class=\"p_pre\" id='lastPage'>末页</a>");

    $("#lastPage").click(function () {
        showProductList(data.pages, pageSize);
    });
}

//逻辑删除商品
function deleteProduct(id) {
    $.ajax({
        url: "easybuy/deleteProduct",
        data: {
            id: id
        },
        success: function (data) {
            if (data == "success") {
                alert("下架成功！");
                showProductList(1, 10);
            } else {
                alert("下架失败，请联系管理员！");
            }
        }
    })
}

//上架商品
function GoodsShelves(id) {
    $.ajax({
        url:"easybuy/putaway",
        data:{
            id:id
        },
        success:function (data) {
            if (data=="success"){
                alert("上架成功！");
                showProductList(1, 10);
            }else {
                alert("上架失败,请与管理员联系！")
            }
        }
    })
}

//修改页面
function updateProduct(id,categorylevel1id,categorylevel2id,categorylevel3id) {
    $(".m_right").empty();

    $.ajax({
        url:"easybuy/product",
        data:{
            productId:id
        },
        success:function (product) {
            $(".m_right").append("<p></p>\n" +
                "            <div class=\"mem_tit\">修改商品</div>\n" +
                "            <div class=\"m_des\">\n" +
                "                <form id='myForm' method='post' enctype='multipart/form-data'>\n" +
                "                    <table border=\"0\" style=\"width:880px;\"  cellspacing=\"0\" cellpadding=\"0\">\n" +
                "                        <input type='hidden' value='"+product.id+"' name='id'>" +
                "                           <tr height=\"45\">\n" +
                "                            <td width=\"200\" align=\"right\">一级分类 &nbsp; &nbsp;</td>\n" +
                "                            <td>\n" +
                "                                <select name=\"categorylevel1id\" style=\"width: 125px;\">\n" +
                "                                </select>\n" +
                "                                &nbsp; <font color=\"#ff4e00\">*</font>\n" +
                "                            </td>\n" +
                "                        </tr>\n" +
                "                        <tr height=\"45\">\n" +
                "                            <td align=\"right\">二级分类 &nbsp; &nbsp;</td>\n" +
                "                            <td>\n" +
                "                                <select name=\"categorylevel2id\" style=\"width: 125px;\">\n"+
                "                                </select>\n" +
                "                                &nbsp; <font color=\"#ff4e00\">*</font>\n" +
                "                            </td>\n" +
                "                        </tr>\n" +
                "                        <tr height=\"45\">\n" +
                "                            <td align=\"right\">三级分类 &nbsp; &nbsp;</td>\n" +
                "                            <td>\n" +
                "                                <select name=\"categorylevel3id\" style=\"width: 125px;\">\n" +
                "                                </select>\n" +
                "                                &nbsp; <font color=\"#ff4e00\">*</font>\n" +
                "                            </td>\n" +
                "                        </tr>\n" +
                "                        <tr height=\"45\">\n" +
                "                            <td align=\"right\">商品名称 &nbsp; &nbsp;</td>\n" +
                "                            <td><input type=\"text\" value=\""+product.name+"\" name=\"name\" class=\"add_ipt\" style=\"width:180px;\" />&nbsp; <font color=\"#ff4e00\">*(必填)</font></td>\n" +
                "                        </tr>\n" +
                "                        <tr height=\"45\">\n" +
                "                            <td align=\"right\">商品图片 &nbsp; &nbsp;</td>\n" +
                "                            <td><img src='http://121.37.168.26:9999/ftpfile/"+product.filename+"' style='height: 50px' alt=''>" +
                "                               <input type=\"file\" value=\"\" name=\"imgs\" style=\"width:180px;\" />&nbsp; <font color=\"#ff4e00\">*</font></td>\n" +
                "                        </tr>\n" +
                "                        <tr height=\"45\">\n" +
                "                            <td align=\"right\">单价 &nbsp; &nbsp;</td>\n" +
                "                            <td><input type=\"text\" value=\""+product.price+"\" name=\"price\" class=\"add_ipt\" style=\"width:180px;\" />&nbsp; <font color=\"#ff4e00\">*</font></td>\n" +
                "                        </tr>\n" +
                "                        <tr height=\"45\">\n" +
                "                            <td align=\"right\">库存 &nbsp; &nbsp;</td>\n" +
                "                            <td><input type=\"text\" value=\""+product.stock+"\" name=\"stock\" class=\"add_ipt\" style=\"width:180px;\" />&nbsp; <font color=\"#ff4e00\">*</font></td>\n" +
                "                        </tr>\n" +
                "                        <tr height=\"45\">\n" +
                "                            <td align=\"right\">描述 &nbsp; &nbsp;</td>\n" +
                "                            <td>\n" +
                "                                <textarea name=\"description\" cols=\"30\" rows=\"5\">"+product.description+"</textarea>\n" +
                "                            </td>\n" +
                "                        </tr>\n" +
                "                        <tr height=\"50\">\n" +
                "                            <td>&nbsp;</td>\n" +
                "                            <td><input type=\"button\" value=\"确定修改\" class=\"btn_tj\" id=\"updateProduct\"/>&nbsp;&nbsp;&nbsp;&nbsp;" +
                "                                   <input type='button'  value='返回' onclick='location.href=\"adminProManage.html\"' class=\"btn_tj\"></td>\n" +
                "                        </tr>\n" +
                "                    </table>\n" +
                "                </form>\n" +
                "            </div>");
            //第一次加载
            stair(categorylevel1id);
            second(categorylevel1id,categorylevel2id);
            reclassify(categorylevel2id,categorylevel3id)

            //当切换分类时加载二级分类
            $("[name='categorylevel1id']").change(function () {
                var categorylevel1id = $("[name='categorylevel1id']").val();
                second(categorylevel1id);
            });
            //当切换分类时加载三级分类
            $("[name='categorylevel2id']").change(function () {
                var categorylevel2id = $("[name='categorylevel2id']").val();
                reclassify(categorylevel2id);
            });
            //判断商品名称不能重复
            $("[name='name']").change(function () {
                var name=$("[name='name']").val();
                $.ajax({
                    url:"easybuy/selectProByName",
                    data:{
                        name:name
                    },
                    success:function (data) {
                        if (data!="success"){
                            alert("商品名称重复了，请重新输入！");
                            $("[name='name']").val("");
                        }
                    }
                })
            });
            $("[name='price']").change(function () {
                var price=$("[name='price']").val();
                var reg=/^\d{1,}$/;
                if (reg.test(price)==false){
                    alert("输入必须为正数!");
                    $(this).val("");
                }
            });
            $("[name='stock']").change(function () {
                var stock=$("[name='stock']").val();
                var reg=/^\d{1,}$/;
                if (reg.test(stock)==false){
                    alert("输入必须为正数!");
                    $(this).val("");
                }
            });
            //修改商品
            $("#updateProduct").click(function () {
                var categorylevel1id=$("[name='categorylevel1id']").val();
                var categorylevel2id=$("[name='categorylevel2id']").val();
                var categorylevel3id=$("[name='categorylevel3id']").val();
                var name=$("[name='name']").val();
                var price=$("[name='price']").val();
                var stock=$("[name='stock']").val();

                if (categorylevel1id==null || categorylevel1id==""){
                    alert("一级分类不能为空！");
                    return ;
                }
                if (categorylevel2id==null || categorylevel2id==""){
                    alert("二级分类不能为空！");
                    return ;
                }
                if (categorylevel3id==null || categorylevel3id==""){
                    alert("三级分类不能为空！");
                    return ;
                }
                if (name==null || name==""){
                    alert("商品名称不能为空！");
                    return ;
                }
                if (price==null || price==""){
                    alert("单价不能为空！");
                    return ;
                }
                if (stock==null || stock==""){
                    alert("库存不能为空！");
                    return ;
                }

                $.ajax({
                    url:"easybuy/updateProduct",
                    type:"post",
                    data:new FormData($("#myForm")[0]),
                    processData: false, //因为data值是FormData对象，不需要对数据做处理。
                    contentType: false,
                    cache: false,
                    success:function (data) {
                        if (data=="success"){
                            alert("修改成功！");
                            location.href="adminProManage.html";
                        }else if (data=="failed"){
                            alert("修改失败，请与管理员联系或者检查网络！");
                        }else {
                            alert("文件上传失败！");
                        }
                    }
                })
            });


        }
    });
}
//加载一级分类
function stair  (categorylevel1id) {
    $.ajax({
        url:"easybuy/procategorylist",
        data:{
            parentId:0
        },
        success:function (categorys1) {
            //加载一级分类
            $.each(categorys1,function (index1,category1) {
                if (category1.id==categorylevel1id){
                    $("[name='categorylevel1id']").append("<option value=\""+category1.id+"\" selected>"+category1.name+"</option>");
                }else {
                    $("[name='categorylevel1id']").append("<option value=\""+category1.id+"\">"+category1.name+"</option>");
                }
            });
        }
    })
}
//加载二级分类
function second(categorylevel1id,categorylevel2id) {
    if(categorylevel1id != '' && categorylevel1id != null){
        $.ajax({
            type:"GET",//请求类型
            url:"easybuy/procategorylist",//请求的url
            data:{parentId:categorylevel1id},//请求参数
            dataType:"json",//ajax接口（请求url）返回的数据类型
            success:function(data){//data：返回数据（json对象）

                for(var i = 0; i < data.length; i++){
                    if (categorylevel2id==data[i].id){
                        options += "<option value=\""+data[i].id+"\" selected>"+data[i].name+"</option>"
                    }else {
                        options += "<option value=\""+data[i].id+"\">"+data[i].name+"</option>";
                    }
                }
                $("[name='categorylevel2id']").html(options);
            },
            error:function(data){//当访问时候，404，500 等非200的错误状态码
                alert("加载二级分类失败！");
            }
        });
    }else{
        $("[name='categorylevel2id']").html("");
        var options = "<option value=\"\">--请选择--</option>";
        $("[name='categorylevel2id']").html(options);
    }
    $("[name='categorylevel3id']").html("");
    var options = "<option value=\"\">--请选择--</option>";
    $("[name='categorylevel3id']").html(options);
}

//加载三级分类
function reclassify(categorylevel2id,categorylevel3id) {
    if(categorylevel2id != '' && categorylevel2id != null){
        $.ajax({
            type:"GET",//请求类型
            url:"easybuy/procategorylist",//请求的url
            data:{parentId:categorylevel2id},//请求参数
            dataType:"json",//ajax接口（请求url）返回的数据类型
            success:function(data){//data：返回数据（json对象）
                for(var i = 0; i < data.length; i++){

                    if (categorylevel3id==data[i].id){
                        options += "<option value=\""+data[i].id+"\" selected>"+data[i].name+"</option>"
                    }else {
                        options += "<option value=\""+data[i].id+"\">"+data[i].name+"</option>";
                    }


                }
                $("[name='categorylevel3id']").html(options);
            },
            error:function(data){//当访问时候，404，500 等非200的错误状态码
                alert("加载三级分类失败！");
            }
        });
    }else{
        $("[name='categorylevel3id']").html("");
        var options = "<option value=\"\">--请选择--</option>";
        $("[name='categorylevel3id']").html(options);
    }
}